<template>
  <view class="order-detail">
    <!-- 订单状态 -->
    <view class="status-section">
      <view class="status-text">{{ getStatusText(orderInfo.orderStatus) }}</view>
    </view>

    <!-- 订单信息 -->
    <view class="order-info">
      <view class="info-item">
        <text class="label">订单号：</text>
        <text class="value">{{ orderInfo.orderNo || orderInfo.id }}</text>
      </view>
      <view class="info-item">
        <text class="label">下单时间：</text>
        <text class="value">{{ formatDate(orderInfo.createTime) }}</text>
      </view>
      <view class="info-item">
        <text class="label">订单金额：</text>
        <text class="value price">¥{{ orderInfo.totalAmount || orderInfo.amount || 0 }}</text>
      </view>
    </view>

    <!-- 商品信息 -->
    <view class="goods-section">
      <view class="section-title">商品信息</view>
      <view class="goods-item" v-for="(item, index) in orderInfo.goodsList" :key="index">
        <image class="goods-image" :src="item.goodsImage" mode="aspectFill"></image>
        <view class="goods-info">
          <view class="goods-name">{{ item.goodsName }}</view>
          <view class="goods-spec">{{ item.goodsSpec }}</view>
          <view class="goods-price">
            <text class="price">¥{{ item.goodsPrice }}</text>
            <text class="quantity">x{{ item.quantity }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 收货地址 -->
    <view class="address-section">
      <view class="section-title">收货地址</view>
      <view class="address-info">
        <view class="contact">{{ orderInfo.receiverName }} {{ orderInfo.receiverPhone }}</view>
        <view class="address">{{ orderInfo.receiverAddress }}</view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-section" v-if="orderInfo.orderStatus === 1">
      <u-button 
        type="primary" 
        @click="handleShipment"
        :loading="isShipping"
      >
        发货
      </u-button>
    </view>
  </view>
</template>

<script>
import { get, put } from '../../utils/request.js'

export default {
  data() {
    return {
      orderId: null,
      orderInfo: {},
      isLoading: false,
      isShipping: false
    }
  },
  
  onLoad(options) {
    if (options.orderId) {
      this.orderId = options.orderId
      this.fetchOrderDetail()
    }
  },
  
  methods: {
    // 获取订单详情
    async fetchOrderDetail() {
      if (!this.orderId) return
      
      this.isLoading = true
      try {
        const response = await get(`/orderst/${this.orderId}`)
        if (response.code === 200) {
          this.orderInfo = response.data || {}
        } else {
          uni.showToast({
            title: '获取订单详情失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取订单详情失败:', error)
        uni.showToast({
          title: '获取订单详情失败',
          icon: 'none'
        })
      } finally {
        this.isLoading = false
      }
    },
    
    // 处理发货
    async handleShipment() {
      if (!this.orderId) return
      
      uni.showModal({
        title: '确认发货',
        content: '确定要发货吗？发货后订单状态将变为待收货',
        success: async (res) => {
          if (res.confirm) {
            await this.updateOrderStatus()
          }
        }
      })
    },
    
    // 更新订单状态
    async updateOrderStatus() {
      this.isShipping = true
      try {
        // 先获取当前订单状态
        const currentResponse = await get(`/orderst/${this.orderId}`)
        if (currentResponse.code !== 200) {
          throw new Error('获取当前订单状态失败')
        }
        
        const currentOrder = currentResponse.data
        const oldStatus = currentOrder.orderStatus
        
        // 更新订单状态为待收货(2)
        const updateData = {
          ...currentOrder,
          orderStatus: 2
        }
        
        const response = await put('/orderst', updateData)
        if (response.code === 200) {
          uni.showToast({
            title: '发货成功！',
            icon: 'success'
          })
          
          // 发送状态更新事件
          uni.$emit('orderStatusUpdated', {
            orderId: this.orderId,
            oldStatus: oldStatus,
            newStatus: 2,
            message: '已发货'
          })
          
          // 返回订单列表
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          throw new Error(response.msg || '发货失败')
        }
      } catch (error) {
        console.error('发货失败:', error)
        uni.showToast({
          title: error.message || '发货失败',
          icon: 'none'
        })
      } finally {
        this.isShipping = false
      }
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待付款',
        1: '待发货',
        2: '待收货',
        3: '已完成'
      }
      return statusMap[status] || '未知状态'
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '未知时间'
      const date = new Date(dateStr)
      return date.toLocaleString('zh-CN')
    }
  }
}
</script>

<style scoped>
.order-detail {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.status-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 40rpx 30rpx;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
}

.status-text {
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
}

.order-info, .goods-section, .address-section {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  color: #333;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  color: #666;
  font-size: 28rpx;
}

.value {
  color: #333;
  font-size: 28rpx;
}

.price {
  color: #ff6b6b;
  font-weight: bold;
}

.goods-item {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.goods-item:last-child {
  border-bottom: none;
}

.goods-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
}

.goods-info {
  flex: 1;
}

.goods-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
  line-height: 1.4;
}

.goods-spec {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.goods-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quantity {
  color: #666;
  font-size: 24rpx;
}

.address-info {
  padding: 20rpx 0;
}

.contact {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.address {
  font-size: 26rpx;
  color: #666;
  line-height: 1.4;
}

.action-section {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-top: 40rpx;
}

.action-section .u-button {
  width: 100%;
  height: 80rpx;
  font-size: 32rpx;
}
</style>
